package com.yunshipei.ui.activity;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.text.TextUtils;

import com.yunshipei.base.BaseActivity;
import com.yunshipei.base.BaseIntentBuilder;
import com.yunshipei.common.Globals;
import com.yunshipei.core.common.XCloudException;
import com.yunshipei.core.utils.YspFunUtils;
import com.yunshipei.enterplorer.R;
import com.yunshipei.manager.YspPreferences;
import com.yunshipei.ui.dialog.DialogHelper;
import com.yunshipei.ui.dialog.WaitDialog;
import com.yunshipei.utils.ToastUtils;

import org.reactivestreams.Publisher;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class GlobalRTSettingsActivity extends BaseActivity {

    @Bind(R.id.et_rt_version)
    protected TextInputEditText etRuntimeVersion;

    private SharedPreferences mPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_global_rtsettings);
        ButterKnife.bind(this);
        mPreferences = YspPreferences.getInstance().getSharedPreferences();
        String lastVersion = mPreferences.getString(Globals.RT_GLOBAL_VERSION, "");
        etRuntimeVersion.setText(lastVersion);
        if (!TextUtils.isEmpty(lastVersion)) {
            etRuntimeVersion.setSelection(lastVersion.length());
        }
    }

    @OnClick(R.id.btn_confirm_rt_version)
    protected void confirmRTVersion() {
        final WaitDialog waitDialog = DialogHelper.getNoCancelableWaitDialog(this, "正在下载运行时...");
        waitDialog.show();
        String version = etRuntimeVersion.getText().toString().trim();
        Flowable.just(version).flatMap(new Function<String, Publisher<String>>() {
            @Override
            public Publisher<String> apply(final String rtVersion) throws Exception {
                if (TextUtils.isEmpty(rtVersion)) {
                    return Flowable.just("");
                }
                String temp = rtVersion;
                int index = temp.indexOf("-");
                if (index != -1) {
                    temp = temp.substring(0, index);
                }
                Pattern pattern = Pattern.compile("[\\d]+\\.[\\d]+\\.[\\d]+");
                Matcher available = pattern.matcher(temp);
                if (!available.matches()) {
                    return Flowable.error(new XCloudException("运行时格式不支持"));
                }
                return YspFunUtils.downloadRT(GlobalRTSettingsActivity.this, rtVersion);
            }
        }).subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<String>() {
            @Override
            public void accept(String rtVersion) throws Exception {
                mPreferences.edit().putString(Globals.RT_GLOBAL_VERSION, rtVersion).apply();
                waitDialog.dismiss();
                ToastUtils.showToast(TextUtils.isEmpty(rtVersion) ? "清空全局运行时设置" : String.format("全局运行时%s设置成功", rtVersion));
                finish();
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                waitDialog.dismiss();
                ToastUtils.showToast(throwable.getMessage());
            }
        });
    }

    public static class GlobalRTSettingsActivityIntentBuilder extends BaseIntentBuilder {

        public GlobalRTSettingsActivityIntentBuilder(Context context) {
            super(context);
        }

        @Override
        protected Class<?> getTargetClazz() {
            return GlobalRTSettingsActivity.class;
        }
    }
}
